#!/usr/bin/env python3
from epics import PV, caget
import datetime

class power(object):
    ''' Power value single channel
        triggered by LLRF
    '''
    @property
    def value_now(self):
        return self.pv.get()

    @property
    def status(self):
        return self.pvname+' = '+str(self.value)

    def onPowerValueChange(self, pvname=None, value=None, conn=None, host=None, timestamp=None, **kwargs):
        #self.print_log('info', 'Current state in onPowerChange: '+str(self.state))
        #self.print_log('debug', 'Current status: '+str(self.state)+self.state_log)
        if self.init_status is True:
            self.value = value
            self.timestamp = timestamp
            self.callback_function()
            if (conn is False):
            	# the place is used to generate alarm of pv losing connection
                if self.logging is None:
                    print('ca connection status changed: ', pvname, conn, host)
                else:
                    self.logging.info('ca connection status changed:  %s %s %s', pvname, conn, host)
            else: pass
        else: pass

    def callback_function(self):
        if callable(self.callback):
            self.callback(self)
        else: pass

    def __init__(self, ssa_dict, callback=None, logging=None, *args, **kwargs):
        self.init_status = False
        self.logging = logging
        self.ssa_brand = ssa_dict['ssa_brand']
        self.ssa_name = ssa_dict['ssa_name']
        self.pickup_name = ssa_dict['pickup_name']
        self.direction = ssa_dict['direction']
        self.callback = callback
        self.pvname = ssa_dict['pvname'][1]
        caget(self.pvname)
        self.pv = PV(self.pvname, callback=self.onPowerValueChange)
        self.value = self.value_now
        self.unit = 'kW'
        self.timestamp = None
        self.init_status = True

    def __del__(self):
        print('Delete ssa.power instance -> '+self.ssa_name+' -> '+self.pvname)

def main():
    pass

if __name__ == '__main__':
    main()
